package com.example.weatherforecast.citypagetool;

import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.weatherforecast.R;

import java.util.List;

/**
 * @Author：coderChen
 * @Package：com.example.weatherforecast.function
 * @Project：WeatherForecast
 * @Date：2023/12/30 22:45
 * @Filename：CityAdapter
 * Explain:添加城市页面->推荐城市列表
 */
public class RecommendCityAdapter extends RecyclerView.Adapter<RecommendCityAdapter.ViewHolder> {
    private List<CityData> cities;
    private SharedPreferences sharedPreferences;

    public RecommendCityAdapter(List<CityData> cities, SharedPreferences sharedPreferences) {
        this.cities = cities;
        this.sharedPreferences = sharedPreferences;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_city, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.bind(cities.get(position));
    }

    @Override
    public int getItemCount() {
        return cities.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvCityName;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvCityName = itemView.findViewById(R.id.tvCityName);

            // 设置点击事件处理
            itemView.setOnClickListener(view -> {
                CityData cityData = cities.get(getAdapterPosition());
                String cityName = cityData.getCityName();
                String cityCode = cityData.getCityCode();

                if (CityDataManager.addCityIfNotExists(cityName, cityCode, sharedPreferences,itemView.getContext())) {
                    Toast.makeText(view.getContext(), "城市添加成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(view.getContext(), "该城市已存在", Toast.LENGTH_SHORT).show();
                }
            });
        }

        public void bind(CityData cityData) {
            tvCityName.setText(cityData.getCityName());
        }
    }
}

